package org.orbis.communicate.indexer.term;

import java.util.concurrent.LinkedBlockingQueue;
import org.orbis.communicate.lock.IndexableSwitch;
import org.orbis.logging.LogParser;
import org.orbis.memorymanager.MemoryManager;

public class TermIndexerClient implements Runnable{
	private static MemoryManager memman;
	private static LinkedBlockingQueue<TermPackage> clientQueue;
	private static Object clientBlockade;

	static{
		clientQueue = new LinkedBlockingQueue<TermPackage>();
		clientBlockade = new Object();
	}

	public TermIndexerClient(boolean isCreateLog){}

	public static void property(MemoryManager manager){
		memman = manager;
	}

	public static void addToQueue(TermPackage newIndex){
		clientQueue.add(newIndex);
	}

	public static boolean isEmpty(){
		return clientQueue.isEmpty();
	}

	public static void waitUntilEmpty(){
		if(!clientQueue.isEmpty()) synchronized(clientBlockade){
			try{
				clientBlockade.wait();
			}catch(InterruptedException e){}
		}
	}

	public static int residue(){
		return clientQueue.size();
	}

	@Override
	public void run(){
		TermPackage newIndex = null;
		long time = 0;
		while(true){
			try{
				newIndex = clientQueue.take();
				time = System.nanoTime();
				if(clientQueue.isEmpty()) synchronized(clientBlockade){
					clientBlockade.notifyAll();
				}
			}catch(InterruptedException e1){}
			time = LogParser.timerFinest("TERM: Take up from client queue", time);

			try{
				IndexableSwitch.waitIfLocked();
			}catch(InterruptedException e){}
			time = LogParser.timerFinest("TERM: Dial switch", time);
			
			if(newIndex == null) break;
			memman.storeTerm(newIndex);
			time = LogParser.timerFinest("TERM: Storing", time);
		}
	}
}
